package top.waikin.mooc.portal.task;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.sql.Connection;

/**
 * 定时任务
 * 定时连接数据库和redis
 * 解决连接池空闲导致的连接超时
 */
@EnableScheduling
@Component
public class ConnectionCheckScheduleTask {
    protected static final Logger LOGGER = LoggerFactory.getLogger(ConnectionCheckScheduleTask.class);

    @Autowired(required = false)
    DataSource dataSource;

    //    @Autowired
//    RedisTemplate<String, Object> redisTemplate;
    @Autowired(required = false)
    RedisConnectionFactory redisConnectionFactory;


    @Scheduled(cron = "0/5 * * * * ?")
    private void checkHikari() {
        try (Connection connection = dataSource.getConnection()) {
            connection.prepareStatement("select 1").execute();
        } catch (Exception e) {
            LOGGER.error("datasource connection fail:{}", e.getMessage());
        }
    }

    @Scheduled(cron = "0/5 * * * * ?")
    private void checkLettuce() {
        try {
//            redisTemplate.opsForValue().set("sync", "true");
            if (redisConnectionFactory instanceof LettuceConnectionFactory) {
                LettuceConnectionFactory lettuceConnectionFactory = (LettuceConnectionFactory) redisConnectionFactory;
                lettuceConnectionFactory.validateConnection();
            }
        } catch (Exception e) {
            LOGGER.error("redis connection fail:{}", e.getMessage());
        }


    }

}
